<?php
/**
 * 单页
 */
namespace App\Service;

use Phalcon\Di;
use App\Models\EwPush;

// const MSG_GO_URL = "http://ysjh5.dev.ewuzhijia.com/msg/"; //详情跳转url

class MsgService  extends BaseService
{
	const READ_FALSE = 0;
	const READ_TRUE  = 1;

	public static function getList($params)
	{
		$where['limit'] = $params->page_num;
		$where['offset'] = ($params->p - 1)*$params->page_num;

		if (isset($params->member_id) && $params->member_id)
			return EwPush::query()
				->columns('id,id AS go_url,to_member_id,title,logo_image,content,is_read,create_time')
				->inWhere('to_member_id',[0,$params->member_id])
				->limit($params->page_num,($params->p-1)*$params->page_num)
				->execute();

		return EwPush::find($where);
	}

	public static function getInfo($raw)
	{
		return EwPush::query()
          	->where('id = :id:')
		  	->bind(['id' => $raw->id])
          	->inWhere('to_member_id',[0,$raw->member_id])
		  	->execute();
	}

	public static function count($params)
	{
		if (isset($params->member_id) && $params->member_id)
			return EwPush::count('to_member_id in (0,' . $params->member_id . ')');

		return EwPush::count();
	}

	/**
	 * [read 已读消息]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function read($id)
	{
		if (isset($id) && $id)
			$data = EwPush::findFirst($id);

		if (!$data)
			return NULL;

		// $redis = Di::getDefault()['redis'];
		// $queue = Di::getDefault()['queue'];

		// $redis->set("MSG_READ_{$id}", $id);
		// $redis->expireAt("MSG_READ_{$id}", time() + 60*5);
		// $queue->put(json_encode([
		// 		"command" => "MSG_READ",
		// 		'id' => $id
		// 	]));

		$data->is_read = self::READ_TRUE;
		return $data->save();
	}
	
	public static function save($data)
	{
		$model = new EwPush();
		return $model->save((array)$data);
	
	}
	
}